package base

import (
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/logger"
	irisRecover "github.com/kataras/iris/v12/middleware/recover"
	"github.com/sirupsen/logrus"
	"red-packet-war/infra"
	"time"
)

var irisAppliation *iris.Application

func Iris() *iris.Application {
	return irisAppliation
}

type IrisServerStarter struct {
	infra.BaseStarter
}

func (i *IrisServerStarter) Init(ctx infra.StarterContext) {
	// 创建iris application实例
	irisAppliation = initIris()
	// 日志组件配置和扩展
	// iris中默认用的室go-logger，统一设置为logrus
	logger := irisAppliation.Logger()
	logger.Install(logrus.StandardLogger())
}

func (i *IrisServerStarter) Start(ctx infra.StarterContext) {
	// 把路由信息打印到控制台
	routes := Iris().GetRoutes()
	for _, r := range routes {
		logrus.Info(r.Name)
	}
	port := ctx.Props().GetDefault("app.server.port", "9090")
	// 启动iris
	Iris().Run(iris.Addr(":" + port))
}

func (i *IrisServerStarter) StartBlocking() bool {
	return true
}

// 主要中间件的配置:recover,日志输出中间件的自定义
func initIris() *iris.Application {
	app := iris.New()
	app.Use(irisRecover.New())
	cfg := logger.Config{
		Status: true,
		IP:     true,
		Method: true,
		Path:   true,
		Query:  true,
		// latency 请求延迟
		LogFunc: func(endTime time.Time, latency time.Duration, status, ip, method, path string, message interface{}, headerMessage interface{}) {
			app.Logger().Infof("| %s | %s | %s | %s | %s | %s | %s | %s |",
				endTime.Format("2006-01-02.15:04:05.000000"), latency.String(), status, ip, method, path, headerMessage, message)
		},
	}
	app.Use(logger.New(cfg))
	return app
}
